/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.store.impl

import com.github.tobato.fastdfs.domain.fdfs.StorePath
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient
import com.gitee.minimalismstyle.fresh.common.core.extra.write
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.store.Store
import org.apache.commons.lang3.time.DateFormatUtils
import org.springframework.stereotype.Service
import java.io.InputStream
import java.io.OutputStream
import java.util.*

/**
 * FastDFS存储文件，支持分布式
 * @author maoxiaodong
 */
@Service
class FastDFSStore(val storageClient: DefaultFastFileStorageClient) : Store {

    override fun write(ossFile: OssFile, inputStream: InputStream): String {
        // 采用年月日设置文件组
        val dateString = DateFormatUtils.format(Date(), "yyyy/MM/dd")
        val storePath = storageClient.uploadFile(dateString, inputStream, ossFile.size!!, ossFile.extName)
        return storePath.fullPath
    }

    override fun read(ossFile: OssFile,  os: OutputStream) {
        val storePath = StorePath.parseFromUrl(ossFile.path)
        storageClient.downloadFile(storePath.group, storePath.path) {
            it.write(os, ossFile.size!!.toInt())
        }
    }

    override fun read(ossFile: OssFile): InputStream {
        val storePath = StorePath.parseFromUrl(ossFile.path)
        var inputStream: InputStream? = null
        storageClient.downloadFile(storePath.group, storePath.path){
            inputStream = it
        }
        return inputStream!!
    }

    override fun delete(path: String) {
        storageClient.deleteFile(path)
    }
}